package com.wxy.favorites.controller;

import com.wxy.favorites.core.PageInfo;
import com.wxy.favorites.entity.Memorandum;
import com.wxy.favorites.security.ContextUtils;
import com.wxy.favorites.security.SecurityUser;
import com.wxy.favorites.service.MemorandumService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/memorandum")
@Api(tags = "备忘录")
@Secured("memorandum")
public class MemorandumController {

    @Autowired
    private MemorandumService memorandumService;

    /**
     * 新增
     *
     * @param memorandum
     * @return
     */
    @PostMapping
    @ApiOperation(value = "保存")
    public void save(@RequestBody Memorandum memorandum) {
        if (memorandum.getId() == null) {// 新建
            memorandumService.saveMemo(memorandum);
        } else {// 修改
            memorandumService.updateMemo(memorandum);
        }
    }

    @GetMapping("/{id}")
    @ApiOperation(value = "根据id查询")
    public Memorandum query(@PathVariable Integer id) {
        return memorandumService.findById(id);
    }

    @GetMapping("/search")
    @ApiOperation(value = "搜索备忘录")
    public List<Memorandum> search(@RequestParam String content) {
        SecurityUser user = ContextUtils.getCurrentUser();
        return memorandumService.findMemorandum(user.getId(), content);
    }

    @GetMapping("/list")
    @ApiOperation(value = "分页查询")
    public PageInfo<Memorandum> list(@RequestParam(required = false) String content, @RequestParam Integer pageNum, @RequestParam Integer pageSize) {
        SecurityUser user = ContextUtils.getCurrentUser();
        return memorandumService.findPageByUserIdAndContentLike(user.getId(), content, pageNum, pageSize);
    }

    @GetMapping("/count")
    @ApiOperation(value = "统计我的备忘录")
    public Long count() {
        SecurityUser user = ContextUtils.getCurrentUser();
        return memorandumService.countByUserId(user.getId());
    }

    @GetMapping("/delete/{id}")
    @ApiOperation(value = "删除备忘录")
    public void delete(@PathVariable Integer id) {
        memorandumService.deleteById(id);
    }

}
